package com.jlcloud.core.xss.config;

import lombok.RequiredArgsConstructor;
import com.jlcloud.core.xss.JlCloudXssProperties;
import com.jlcloud.core.xss.XssInterceptor;
import com.jlcloud.core.xss.processor.DefaultXssCleaner;
import com.jlcloud.core.xss.processor.FormXssClean;
import com.jlcloud.core.xss.processor.JacksonXssClean;
import com.jlcloud.core.xss.processor.XssCleaner;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Nonnull;

/**
 * jackson xss 配置
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
@AutoConfiguration
@RequiredArgsConstructor
@EnableConfigurationProperties(JlCloudXssProperties.class)
@ConditionalOnProperty(
	prefix = JlCloudXssProperties.PREFIX,
	name = "enabled",
	havingValue = "true",
	matchIfMissing = true
)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class JlCloudXssConfiguration implements WebMvcConfigurer {
	private final JlCloudXssProperties xssProperties;

	@Bean
	@ConditionalOnMissingBean
	public XssCleaner xssCleaner(JlCloudXssProperties properties) {
		return new DefaultXssCleaner(properties);
	}

	@Bean
	public FormXssClean formXssClean(JlCloudXssProperties properties,
                                     XssCleaner xssCleaner) {
		return new FormXssClean(properties, xssCleaner);
	}

	@Bean
	public Jackson2ObjectMapperBuilderCustomizer xssJacksonCustomizer(JlCloudXssProperties properties,
                                                                      XssCleaner xssCleaner) {
		return builder -> builder.deserializerByType(String.class, new JacksonXssClean(properties, xssCleaner));
	}

	@Override
	public void addInterceptors(@Nonnull InterceptorRegistry registry) {
		XssInterceptor interceptor = new XssInterceptor(xssProperties);
		registry.addInterceptor(interceptor)
			.addPathPatterns(xssProperties.getBlockUrl())
			.addPathPatterns(xssProperties.getSkipUrl())
			.order(Ordered.LOWEST_PRECEDENCE);
	}

}
